<template>
  <el-dialog
    :model-value="visible"
    :title="title"
    :width="width"
    :show-close="showClose"
    :draggable="draggable"
    :close-on-click-modal="false"
    :top="top"
    :before-close="handleBeforeClose"
    @update:model-value="handleUpdateVisible"
  >
    <!-- 默认插槽，用于传递弹窗内容 -->
    <slot></slot>

    <!-- 底部插槽，用于自定义底部按钮 -->

    <template #footer>
      <!-- 如果父组件传递了 footer 插槽内容，则使用父组件的内容 -->
      <div class="dialog-footer">
        <div v-for="(button, index) in buttons" :key="index">
          <el-button @click="button.click" :type="button.type">{{
            button.text
          }}</el-button>
        </div>
      </div>
      <slot name="footer" v-if="!buttons || buttons.length === 0">
        <!-- 默认按钮 -->
        <el-button @click="handleCancel" v-if="iSshowCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </slot>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits } from "vue";

// 定义 Props
const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  visible: {
    type: Boolean,
    default: false,
  },
  width: {
    type: String,
    default: "30%",
  },
  beforeClose: {
    type: Function,
    default: null,
  },
  showClose: {
    type: Boolean,
    default: true,
  },
  draggable: {
    type: Boolean,
    default: false,
  },
  top: {
    type: String,
    default: "50px",
  },
  iSshowCancel: {
    type: Boolean,
    default: true,
  },
  buttons: {
    type: Array,
  },
});

// 定义 Emits
const emit = defineEmits(["update:visible", "confirm", "cancel", "close"]);

// 处理弹窗关闭前的逻辑
const handleBeforeClose = (done) => {
  if (props.beforeClose) {
    props.beforeClose(done);
  } else {
    done();
  }
};

// 处理 visible 的更新
const handleUpdateVisible = (value) => {
  emit("update:visible", value);
};

// 处理取消按钮点击
const handleCancel = () => {
  emit("cancel");
  emit("update:visible", false);
  emit("close");
};

// 处理确定按钮点击
const handleConfirm = () => {
  emit("confirm");
  emit("update:visible", false);
  emit("close");
};
</script>

<style scoped lang="scss">
/* 统一封装按钮样式 */
.dialog-footer {
  display: flex;
  align-items: end;
  justify-content: flex-end;
  gap: 5px;
  width: 100%;
  /* 按钮之间的间距 */
}

.dialog-footer :deep(.el-button) {
  width: 78%;
  white-space: nowrap;
  padding: 10px 20px;
  /* 统一按钮内边距 */
  font-size: 14px;
  /* 统一字体大小 */
  border-radius: 8px;
  /* 统一圆角 */
}

.dialog-footer :deep(.el-button--primary) {
  background-color: #409eff;
  /* 主按钮背景色 */
  border-color: #409eff;
  /* 主按钮边框色 */
}

.dialog-footer :deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  /* 主按钮悬停背景色 */
  border-color: #66b1ff;
  /* 主按钮悬停边框色 */
}

.divider {
  height: 1px;
  width: 100%;
  background-color: #000000c4;
  /* 分割线颜色 */
  margin: 5px 0;
  /* 上下边距 */
}
</style>